﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Content;
using MethodWorx.CMS.Requests;
using MethodWorx.CMS.Services;
using MethodWorx.CMS.Plugins;

namespace MethodWorx.CMS.Workflow.CreatePage
{
    public class CreatePageWorkflowComponent : WorkflowComponent<CreateCreatePageConfigurationController>
    {
        public CreatePageWorkflowComponent(Plugin plugin)
            : base(plugin)
        {
        }

        public static Guid ComponentId = Guid.Parse("{D05F11D4-B959-4E29-9787-7836538E03C6}");

        public override Guid Id
        {
            get { return ComponentId;  }
        }

        public override string Category
        {
            get { return "Content";  }
        }

        public override string Name
        {
            get { return "Create Page";  }
        }

        public override string Description
        {
            get { return "Creates a page";  }
        }

        public override string View
        {
            get { return "CreatePageConfigurationView.ascx"; }
        }

        public override StepExecutionResult Execute(IWorkflowExecutionContext context, IWorkflowConfiguration configuration)
        {
            //
            //  ok, here we go..
            var currentPage = context.GetWorkflowValue("currentPage") as Page;
            var config = configuration as CreatePageConfiguration;

            if(config != null && currentPage != null)
            {
                //
                //  ok, here is our current page..  
                //  so lets create a content item
                var service = new ContentService(context.CmsDataProvider);

                //  get the name from the configuration
                var created = service.CreatePage(
                    currentPage, 
                    Guid.Parse(this.ParseString(config.PageTemplate, context.GetAllWorkflowValues())),
                    this.ParseString(config.PageName, context.GetAllWorkflowValues()), 
                    config.UseAutoIncrementingName,
                    config.Publish);

                //  return the created item
                return StepExecutionResult.Ok(created);

            }
            else
                return StepExecutionResult.Error("Unexpected Workflow Error, invalid configuration");
        }
    }
}
